package com.hcms.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.hcms.admin.dto.CmsModuleOptionResponse;
import com.hcms.admin.service.ICmsModuleService;
import com.hcms.mybatis.entity.CmsModule;
import com.hcms.mybatis.mapper.CmsModuleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 模块配置表 服务实现类
 * </p>
 *
 * @author achenxw@126.com
 * @since 2023-04-01
 */
@Service
public class CmsModuleServiceImpl extends ServiceImpl<CmsModuleMapper, CmsModule> implements ICmsModuleService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CmsModuleMapper cmsModuleMapper;

    @Override
    public List<CmsModule> getList(Integer pageNum, Integer pageSize) {
        logger.info("Run getList(), pageNum={}, pageSize={}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize, "sort ASC, id DESC");
        LambdaQueryWrapper<CmsModule> queryWrapper = new LambdaQueryWrapper<>();
        return cmsModuleMapper.selectList(queryWrapper);
    }

    @Override
    public CmsModule getView(Long id) {
        logger.info("Run getView(), id={}", id);
        return cmsModuleMapper.selectById(id);
    }

    @Override
    public int createItem(CmsModule entity) {
        logger.info("Run createItem()");
        entity.setCreateTime(new Date());
        return cmsModuleMapper.insert(entity);
    }

    @Override
    public int updateItem(Long id, CmsModule entity) {
        logger.info("Run updateItem(), id={}", id);
        entity.setId(id);
        return cmsModuleMapper.updateById(entity);
    }

    @Override
    public int deleteItem(String ids) {
        logger.info("Run deleteItem(), ids={}", ids);
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<Long> collect = list.stream().map(Long::parseLong).collect(Collectors.toList());
        return cmsModuleMapper.deleteBatchIds(collect);
    }

    @Override
    public List<CmsModuleOptionResponse> getOptions() {
        logger.info("Run getOptions()");
        LambdaQueryWrapper<CmsModule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CmsModule::getId, CmsModule::getModuleName);
        queryWrapper.orderByAsc(CmsModule::getSort);
        queryWrapper.orderByDesc(CmsModule::getId);
        List<CmsModule> cmsModules = cmsModuleMapper.selectList(queryWrapper);
        return cmsModules.stream().map(CmsModuleOptionResponse::new).collect(Collectors.toList());
    }

}
